#include "s_lock_buzzer.h"

#define S_BUZZER_ENABLE     1
////////////////////////////////////////////////////////////////////////////////
#include "h_stm32_hal_defines.h"
#include <stdio.h>
#include "h_stm32_hal_timer.h"

#define BUZZER_PWM_TIME     htim1

extern TIM_HandleTypeDef BUZZER_PWM_TIME;

#define s_lock_buzzer_delay                     delay_ms//osDelay//HAL_Delay
// #define s_lock_buzzer_pwm_change_frq(x)         __HAL_TIM_SET_COMPARE(&BUZZER_PWM_TIME, TIM_CHANNEL_1, x)



#define s_lock_buzzer_pwm_start()               \
    HAL_TIMEx_PWMN_Start(&BUZZER_PWM_TIME, TIM_CHANNEL_1)
#define s_lock_buzzer_pwm_stop()                \
    HAL_TIMEx_PWMN_Stop(&BUZZER_PWM_TIME, TIM_CHANNEL_1)

static void s_lock_buzzer_pwm_change_frq(unsigned int frq)
{
#if S_BUZZER_ENABLE
    unsigned int new_main_fep_divide = 0U;

    new_main_fep_divide = (1024000.0 / frq);

    /* Set the Autoreload value */
    BUZZER_PWM_TIME.Instance->ARR = new_main_fep_divide;

    /* Set the Capture Compare Register value */
    BUZZER_PWM_TIME.Instance->CCR1 = new_main_fep_divide / 2;
#endif
}


////////////////////////////////////////////////////////////////////////////////

signed char S_Lock_Buzzer_Success(void)
{
    s_lock_buzzer_pwm_start();

    s_lock_buzzer_pwm_change_frq(294);
    s_lock_buzzer_delay(160);

    s_lock_buzzer_pwm_change_frq(589);
    s_lock_buzzer_delay(83);

    s_lock_buzzer_pwm_change_frq(661);
    s_lock_buzzer_delay(83);

    s_lock_buzzer_pwm_change_frq(700);
    s_lock_buzzer_delay(83);

    s_lock_buzzer_pwm_change_frq(786);
    s_lock_buzzer_delay(83);
    s_lock_buzzer_pwm_stop();
    return 0;
}

signed char S_Lock_Buzzer_DeSuccess(void)
{
    s_lock_buzzer_pwm_start();

    s_lock_buzzer_pwm_change_frq(786);
    s_lock_buzzer_delay(83);

    s_lock_buzzer_pwm_change_frq(700);
    s_lock_buzzer_delay(83);

    s_lock_buzzer_pwm_change_frq(661);
    s_lock_buzzer_delay(83);

    s_lock_buzzer_pwm_change_frq(589);
    s_lock_buzzer_delay(83);

    s_lock_buzzer_pwm_change_frq(294);
    s_lock_buzzer_delay(160);

    s_lock_buzzer_pwm_stop();
    return 0;
}

signed char S_Lock_Buzzer_Failed(void)
{
    s_lock_buzzer_pwm_start();
                
    s_lock_buzzer_pwm_change_frq(294);
    s_lock_buzzer_delay(300);

    s_lock_buzzer_pwm_stop();
    s_lock_buzzer_delay(83);
    s_lock_buzzer_pwm_start();

    s_lock_buzzer_pwm_change_frq(294);
    s_lock_buzzer_delay(300);

    s_lock_buzzer_pwm_stop();
    return 0;
}


signed char S_Lock_Buzzer_KeyDown(void)
{
    s_lock_buzzer_pwm_start();
                
    s_lock_buzzer_pwm_change_frq(589);
    s_lock_buzzer_delay(50);

    s_lock_buzzer_pwm_stop();
    return 0;
}




void S_Lock_Buzzer_Test(void)
{
    S_Lock_Buzzer_Success();

    delay_ms(1000);

    S_Lock_Buzzer_Failed();
}
